#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
# import ast
import tornado.web
import tornado.ioloop


class Handler(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    def get(self):
        self.write("I'm alive!")


class SmsHandler(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    def get(self):
        self.write("I'm sms!")

    def post(self):
        post_data = self.request.body.decode('utf-8')
        post_args = json.loads(post_data)
        # json.loads后还是 str，所以添加eval， I'm not kiding
        # post_args = ast.literal_eval(post_args)

        appid = post_args.get('appid')
        sid = post_args.get('sid')
        tranid = post_args.get('tranid')
        send_time = int(post_args.get('timestamp'))
        sign = post_args.get('sign')
        data = post_args.get('data')

        sqls = []
        for report in data:
            mobile = int(report.get('mobile'))
            report_status = report.get('report_status')
            if report_status == 'success':
                status = 1
            else:
                status = 0
            sql = f'''insert into sms_notify(appid, sid, tranid, send_time, mobile, status) values('{appid}', '{sid}', '{tranid}', {send_time}, {mobile}, {status})'''
            sqls.append(sql)
        self.application.db.execute(sqls)
        self.application.db.commit()
        # ret_dic = {"code": 200, "message": "ok", "data": {'sign': sign}}
        ret_dic = {'result': 'succ'}
        ret_str = json.dumps(ret_dic)
        self.write(ret_str)
